import 'dart:convert';
import 'package:flutter/foundation.dart' show kDebugMode;
import 'package:http/http.dart' as http;
import '../models/collect.dart';
import '../models/category.dart';
import '../models/api_response.dart';

class ApiService {
  // Debug模式和Release模式的API地址配置
  static const String _debugBaseUrl = 'http://localhost:18886/';
  static const String _releaseBaseUrl = 'https://liufq.cn/api/';

  // 根据运行模式自动切换baseUrl
  static String get currentHost => kDebugMode ? _debugBaseUrl : _releaseBaseUrl;

  /// 统一日志打印方法
  static void _logRequest({
    required String method,
    required String url,
    Map<String, String>? headers,
    String? body,
    Map<String, dynamic>? params,
  }) {
    print('=== API请求 ===');
    print('Method: $method');
    print('URL: $url');
    if (headers != null) {
      print('Headers: $headers');
    }
    if (params != null) {
      print('Params: $params');
    }
    if (body != null) {
      print('Request Body: $body');
    }
  }

  static void _logResponse({
    required int statusCode,
    required String body,
    Map<String, dynamic>? extras,
  }) {
    print('Status Code: $statusCode');
    print('Response Body: $body');
    if (extras != null) {
      extras.forEach((key, value) {
        print('$key: $value');
      });
    }
    print('===============');
  }

  /// 获取收藏列表
  static Future<List<CollectionItem>> getCollectionList({
    String? categoryId,
    bool? isFavorite,
  }) async {
    try {
      final queryParams = <String, String>{};
      if (categoryId != null && categoryId.isNotEmpty) {
        queryParams['categoryId'] = categoryId;
      }
      if (isFavorite != null) {
        queryParams['isFavorite'] = isFavorite.toString();
      }

      final url = Uri.parse('${currentHost}collect/list').replace(
        queryParameters: queryParams.isNotEmpty ? queryParams : null,
      );
      _logRequest(method: 'GET', url: url.toString(), params: queryParams);

      final response = await http.get(url);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(
          jsonData,
          (data) {
            if (data is List) {
              return data
                  .map((item) => CollectionItem.fromJson(item))
                  .toList();
            }
            return <CollectionItem>[];
          },
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data as List<CollectionItem>;
        }
      }

      return [];
    } catch (e) {
      print('获取收藏列表失败: $e');
      return [];
    }
  }

  /// 创建收藏
  static Future<void> createCollection({
    required String title,
    required String content,
    String? discuss,
    String? source,
    String? categoryId,
    List<String>? tags,
  }) async {
    try {
      final url = Uri.parse('${currentHost}collect/create');
      final requestBody = {
        'title': title,
        'content': content,
        if (discuss != null && discuss.isNotEmpty) 'discuss': discuss,
        if (source != null && source.isNotEmpty) 'source': source,
        if (categoryId != null && categoryId.isNotEmpty) 'categoryId': categoryId,
        if (tags != null && tags.isNotEmpty) 'tags': tags,
      };
      final headers = {'Content-Type': 'application/json'};
      final bodyString = json.encode(requestBody);

      _logRequest(
        method: 'POST',
        url: url.toString(),
        headers: headers,
        body: bodyString,
      );

      final response = await http.post(url, headers: headers, body: bodyString);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '创建失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('创建收藏失败: $e');
      rethrow;
    }
  }

  /// 更新收藏
  static Future<void> updateCollection({
    required String id,
    required String title,
    required String content,
    String? discuss,
    String? source,
    String? categoryId,
    List<String>? tags,
  }) async {
    try {
      final url = Uri.parse('${currentHost}collect/$id');
      final requestBody = {
        'title': title,
        'content': content,
        if (discuss != null && discuss.isNotEmpty) 'discuss': discuss,
        if (source != null && source.isNotEmpty) 'source': source,
        if (categoryId != null && categoryId.isNotEmpty) 'categoryId': categoryId,
        if (tags != null && tags.isNotEmpty) 'tags': tags,
      };
      final headers = {'Content-Type': 'application/json'};
      final bodyString = json.encode(requestBody);

      _logRequest(
        method: 'PUT',
        url: url.toString(),
        headers: headers,
        body: bodyString,
        params: {'id': id},
      );

      final response = await http.put(url, headers: headers, body: bodyString);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        if (response.body.isEmpty) {
          print('更新成功：空响应体');
          return; // 更新成功，返回空响应
        }

        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '更新失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('更新收藏失败: $e');
      rethrow;
    }
  }

  /// 删除收藏
  static Future<void> deleteCollection(String id) async {
    try {
      final url = Uri.parse('${currentHost}collect/$id');

      _logRequest(
        method: 'DELETE',
        url: url.toString(),
        params: {'id': id},
      );

      final response = await http.delete(url);

      _logResponse(
        statusCode: response.statusCode,
        body: response.body,
        extras: {'Body Length': response.body.length},
      );

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        if (response.body.isEmpty) {
          print('删除成功：空响应体');
          return; // 删除成功，返回空响应
        }

        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        print('解析的JSON: $jsonData');
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        print('API Response Success: ${apiResponse.isSuccess}');
        print('API Response Message: ${apiResponse.message}');

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '删除失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('删除收藏失败: $e');
      rethrow;
    }
  }

  /// 获取分类列表
  static Future<List<Category>> getCategoryList() async {
    try {
      final url = Uri.parse('${currentHost}category/list?type=COLLECT');
      _logRequest(method: 'GET', url: url.toString());

      final response = await http.get(url);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(
          jsonData,
          (data) {
            if (data is List) {
              return data.map((item) => Category.fromJson(item)).toList();
            }
            return <Category>[];
          },
        );

        if (apiResponse.isSuccess && apiResponse.data != null) {
          return apiResponse.data as List<Category>;
        }
      }

      return [];
    } catch (e) {
      print('获取分类列表失败: $e');
      return [];
    }
  }

  /// 更新收藏的喜欢状态
  static Future<void> updateFavoriteStatus({
    required String id,
    required bool isFavorite,
  }) async {
    try {
      final url = Uri.parse('${currentHost}collect/$id');
      final requestBody = {
        'isFavorite': isFavorite,
      };
      final headers = {'Content-Type': 'application/json'};
      final bodyString = json.encode(requestBody);

      _logRequest(
        method: 'PUT',
        url: url.toString(),
        headers: headers,
        body: bodyString,
        params: {'id': id},
      );

      final response = await http.put(url, headers: headers, body: bodyString);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        if (response.body.isEmpty) {
          print('更新喜欢状态成功：空响应体');
          return;
        }

        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '更新喜欢状态失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('更新喜欢状态失败: $e');
      rethrow;
    }
  }

  /// 更新展示类型
  static Future<void> updateShowType({
    required String id,
    required int showType,
  }) async {
    try {
      final url = Uri.parse('${currentHost}collect/$id');
      final requestBody = {
        'showType': showType,
      };
      final headers = {'Content-Type': 'application/json'};
      final bodyString = json.encode(requestBody);

      _logRequest(
        method: 'PUT',
        url: url.toString(),
        headers: headers,
        body: bodyString,
        params: {'id': id},
      );

      final response = await http.put(url, headers: headers, body: bodyString);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        if (response.body.isEmpty) {
          print('更新展示类型成功：空响应体');
          return;
        }

        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '更新展示类型失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('更新展示类型失败: $e');
      rethrow;
    }
  }

  /// 创建分类
  static Future<void> createCategory({
    required String name,
    String? parentId,
  }) async {
    try {
      final url = Uri.parse('${currentHost}category/create');
      final requestBody = {
        'type': 'COLLECT',
        'name': name,
        if (parentId != null && parentId.isNotEmpty) 'parentId': parentId,
      };
      final headers = {'Content-Type': 'application/json'};
      final bodyString = json.encode(requestBody);

      _logRequest(
        method: 'POST',
        url: url.toString(),
        headers: headers,
        body: bodyString,
      );

      final response = await http.post(url, headers: headers, body: bodyString);
      _logResponse(statusCode: response.statusCode, body: response.body);

      if (response.statusCode == 200) {
        // 检查响应体是否为空
        if (response.body.isEmpty) {
          print('创建分类成功：空响应体');
          return;
        }

        final jsonData = json.decode(utf8.decode(response.bodyBytes));
        final apiResponse = ApiResponse.fromJson(jsonData, (data) => data);

        if (!apiResponse.isSuccess) {
          throw Exception(apiResponse.message ?? '创建分类失败');
        }
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('创建分类失败: $e');
      rethrow;
    }
  }
}
